<?php
/**
 * User: @lixu
 * Date: 2019-05-13
 * Time: 15:42
 */

namespace Biz\service\esSearch;

use Biz\cache\wiki\GoodsHot;
use Biz\module\Search\WikiSearch;
use Biz\tools\FormatDate;
use Doraemon\tools\Log;

class Wiki
{
    const SCENES_APP_SHOP_WIKI_LIST = 'shop_wiki_list'; // 商家主页商品
    const SCENES_APP_TAG_LIST = 'app_tag_list'; // tag列表页
    const SCENES_APP_CATEGORY_LIST = 'app_category_list'; // 分类列表页
    const SCENES_APP_PRESET_CONDITION = 'app_preset_condition'; // 预设条件
    const SCENES_SHOP_ADMIN_CATEGORY_WIKI_CARD = 'shop_admin_category_wiki_card'; // 后台分类wiki卡片
    const SCENES_APP_WIKI_CATEGORY_CARD = 'app_wiki_category_card'; // 首页推荐wiki分类卡片
    const SCENES_WIKI_CATEGORY_HOT = 'wiki_category_hot'; // 分会场推荐wiki卡片

    public static function pageExtend($last_category_id)
    {
        $where = [
            'last_category_id' => $last_category_id
        ];

        $list = self::getList($where, self::SCENES_WIKI_CATEGORY_HOT);

        return $list['rows'] ?? [];
    }

    public static function getListForClassify(array $where = [], $scenes = null, $sortType = 0, $page = 1, $pageSize = 20, $field = ['id'], $start = null)
    {
        $result = ['total' => 0, 'is_over' => 1, 'rows' => []];

        if (is_null($scenes)) {
            return $result;
        } else {
            $where['scenes'] = $scenes;
        }

        if (!isset($where['ORDER'])) {
            $where['ORDER'] = self::sortTypeMapping($sortType);
        }

        $params['query'] = json_encode($where, JSON_UNESCAPED_UNICODE);

        if (is_array($field)) {
            $params['fl'] = implode(",", $field);
        } else {
            $params['fl'] = $field;
        }

        $params['page'] = $page;
        $params['page_size'] = $pageSize;

        $result = WikiSearch::getList($params);

        if (isset($result['data'])) {
            $result = $result['data'];
            $list['total'] = $result['hits']['total'];
            $list['rows'] = $result['hits']['total'] ? self::formatGoodsListForClassify($result['hits']['hits'], $field) : [];

            $list['is_over'] = count($result['hits']['hits']) >= $pageSize ? 0 : 1;

            if (isset($result['aggregations'])) {
                $list['aggregations'] = $result['aggregations'];
            }

            return $list;
        } else {
            return ['total' => 0, 'is_over' => 1, 'rows' => []];
        }
    }

    public static function getList(array $where = [], $scenes = null, $sortType = 0, $page = 1, $pageSize = 20, $field = ['id'], $start = null)
    {
        $result = ['total' => 0, 'is_over' => 1, 'rows' => []];

        if (is_null($scenes)) {
            return $result;
        } else {
            $where['scenes'] = $scenes;
        }

        if (!isset($where['ORDER'])) {
            $where['ORDER'] = self::sortTypeMapping($sortType);
        }

        $params['query'] = json_encode($where, JSON_UNESCAPED_UNICODE);

        if (is_array($field)) {
            $params['fl'] = implode(",", $field);
        } else {
            $params['fl'] = $field;
        }

        $params['page'] = $page;
        $params['page_size'] = $pageSize;

        $result = WikiSearch::getList($params);

        if (isset($result['data'])) {
            $result = $result['data'];
            $list['total'] = $result['hits']['total'];
            $list['rows'] = $result['hits']['total'] ? self::formatGoodsList($result['hits']['hits'], $field) : [];
            $list['is_over'] = count($result['hits']['hits']) >= $pageSize ? 0 : 1;

            if (isset($result['aggregations'])) {
                $list['aggregations'] = $result['aggregations'];
            }

            return $list;
        } else {
            return ['total' => 0, 'is_over' => 1, 'rows' => []];
        }
    }

    private static function sortTypeMapping($sortType)
    {
        $sortMapping = [
            ['hot_rank' => 'DESC'],
            ['addtime' => 'DESC'],
        ];

        return $sortMapping[$sortType];
    }

    // 根据wiki id 更新es wiki info
    public static function saveWikiInfoByWikiId($wikiId)
    {
        if ($wikiId) {
            $wikiInfo = \Biz\model\wiki\Wiki::getByWhere(
                array(
                    "id" => $wikiId
                )
            );

            // wiki info
            if (is_array($wikiInfo) && $wikiInfo) {
                $wikiInfo = self::formatWikiBasicInfo($wikiInfo);
                self::saveByWikiId($wikiInfo);
            }
        }
    }

    /**
     * 上层代码控制要同步的数据
     * @param $wikiInfo
     * @return bool
     */
    public static function saveByWikiId($wikiInfo)
    {
        if (!$wikiInfo['id']) {
            return false;
        }
        $result = WikiSearch::save($wikiInfo);
        return $result;
    }

    /**
     * 监听binlog同步数据
     * @param $list
     */
    public static function syncSave($list)
    {
        Log::info('table:' . $list['table'] . '#data:' . json_encode($list['data'], JSON_UNESCAPED_UNICODE));
        $info = self::formatWikiBasicInfo($list['data']);
        // wiki 表更新 同步更新 wiki basic表
        if (isset($list['data']["basic_id"]) && $list['data']["basic_id"]) {
            WikiBasic::saveDataById($list['data']["basic_id"]);
        }
        $result = WikiSearch::save($info);

        Log::debug('table:' . $list['table'] . '#wiki-debug', $result);
    }

    /**
     * 监听binlog同步数据
     * @param $list
     */
    public static function syncSaveContent($list)
    {
        Log::info('table:' . $list['table'] . '#data:' . json_encode($list['data'], JSON_UNESCAPED_UNICODE));
        $info = self::formatWikiContentInfo($list['data']);
        $result = WikiSearch::save($info);

        Log::debug('table:' . $list['table'] . '#wiki-content-debug', $result);
    }

    private static function formatWikiBasicInfo($data)
    {
        $data['addtime'] = FormatDate::formatDate($data['addtime']);
        $data['edittime'] = FormatDate::formatDate($data['edittime']);

        // 品牌信息
        $data['brand_type'] = \Biz\model\brand\Brand::BRAND_TYPE_DEFAULT;
        if (isset($data["brand_id"]) && $data["brand_id"]) {
            $brandInfo = \Biz\model\brand\Brand::getBrandInfoById($data["brand_id"]);

            if (is_array($brandInfo) && $brandInfo) {
                $data['brand_type'] = $brandInfo["brand_type"];
            }
        }

        // 商品热度
        $data['basic_goods_hot'] = 0;
        $rdsGoodsHot = GoodsHot::getGoodsHotById($data["basic_id"]);
        $data['basic_goods_hot'] = $rdsGoodsHot ? $rdsGoodsHot : 0;

        // 住友note关联wiki的时间
        $data["obj_last_relate_time"] = \Biz\service\wiki\ObjRelateWiki::getLastWikiRelateTime($data["id"]);

        return $data;
    }

    private static function formatWikiContentInfo($data)
    {
        return [
            'id' => $data['wiki_id'],
            'imgs' => $data['imgs'],
            'content' => $data['content'],
        ];
    }

    private static function formatGoodsList($goodsList, $field)
    {
        $list = [];
        foreach ($goodsList as $value) {
            if (!is_array($field)) {
                $list[] = $value['_source'];
            } else if (count($field) == 1) {
                $list[] = $value['_source'][current($field)];
            } else {
                $list[] = $value['_source'];
            }
        }
        return $list;
    }

    private static function formatGoodsListForClassify($goodsList, $field)
    {
        $list = [];
        foreach ($goodsList as $value) {
            if (!is_array($field)) {
                $list[] = $value['_source'];
            } else if (count($field) == 1) {
                $formatData = array(
                    current($field) => $value['_source'][current($field)],
                    "weight" => $value["sort"][0]
                );
                $list[] = $formatData;
            } else {
                $list[] = $value['_source'];
            }
        }
        return $list;
    }
}